package org.bing.engine.common.scheduler;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SimpleTaskContainer {

    protected static final Log logger = LogFactory.getLog(SingleTaskContainer.class);
    protected static final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    protected SimpleScheduler scheduler;

    public void setScheduler(SimpleScheduler scheduler) {
        this.scheduler = scheduler;
    }

    public void schedule(TaskWrapper wrapper, boolean override) {
        String name = wrapper.getName();
        try {
            doSchedule(name, wrapper, override);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void schedule(TaskWrapper wrapper) {
        this.schedule(wrapper, false);
    }

    @SuppressWarnings("rawtypes")
    public void schedule(AbstractTask task) {
        if (task instanceof TaskWrapper) {
            this.schedule((TaskWrapper) task);
        } else {
            Class targetClz = task.getClass();
            this.schedule(targetClz.getName(), task);
        }
    }

    public void schedule(String name, AbstractTask task) {
        try {
            doSchedule(name, task, false);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void doSchedule(String name, AbstractTask task, boolean override) throws Exception {
        Date begin = null, end = null;
        if (task.getBegin() == null || task.getBegin().trim().length() == 0) {
            begin = new Date();
        } else {
            begin = sdf.parse(task.getBegin());
        }
        if (task.getEnd() == null || task.getEnd().trim().length() == 0) {
            end = new Date(Long.MAX_VALUE);
        } else {
            end = sdf.parse(task.getEnd());
        }
        if (task.isIntegral()) {
            long time = begin.getTime();
            long period = task.getPeriod() * 1000;
            long rem = time % period;
            if (rem > 0) {
                time = time + period - rem;
                begin = new Date(time);
            }
        }
        scheduler.schedule(name, task, begin, end, task.getPeriod(), override);
    }

    public void cancel(String name) {
        this.scheduler.cancel(name);
    }
}